package net.hn.hnms.sys.common.mybatis.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.sys.common.core.exception.ServiceException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.core.web.domain.BaseEntity;
import net.hn.hnms.sys.common.mybatis.config.MybatisMineCodeConfiguration;
import net.hn.hnms.sys.common.satoken.utils.LoginHelper;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author Lion Li
 * @date 2021/4/25
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    @Autowired(required = false)
    private MybatisMineCodeConfiguration.MineCode mineCode;


    @Override
    public void insertFill(MetaObject metaObject) {
        //自动填充字段值的配置
        //创建时间
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        //创建人id
        this.strictInsertFill(metaObject, "createUserId", String.class,getLoginUserInfo()==null?"":getLoginUserInfo().getUserId().toString());
        //创建时同时初始化更新人id
        this.strictInsertFill(metaObject, "updateUserId", String.class,getLoginUserInfo()==null?"":getLoginUserInfo().getUserId().toString());
        //创建时同时初始化更新时间
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        //煤矿编码
        // todo 读取方式待定 暂时为"620824009734"
//        this.strictInsertFill(metaObject, "mineCode", String.class, "620824009734");
        //获取配置文件中煤矿编码
        //判断enable是否启动的公司端
        if ("meiye".equals(mineCode.getEnable())||"beineng".equals(mineCode.getEnable()) || "huating".equals(mineCode.getEnable()) || "zhamei".equals(mineCode.getEnable()) || "qingyang".equals(mineCode.getEnable())) {
            this.strictInsertFill(metaObject, "companyCode", String.class, mineCode.getCode());
        } else {
            this.strictInsertFill(metaObject, "mineCode", String.class, mineCode.getCode());
        }
        //根据登陆人获取煤矿编码
//        LoginUser loginUserInfo = getLoginUserInfo();
//        String organizationCode = loginUserInfo.getOrganizationCode();
//        this.strictInsertFill(metaObject,  "mineCode", String.class, organizationCode);
        //删除标记
        this.strictInsertFill(metaObject, "delFlag", String.class, "0");

        this.strictInsertFill(metaObject,"createdAt",Date.class,new Date());
        this.strictInsertFill(metaObject,"updatedAt",Date.class,new Date());
        this.strictInsertFill(metaObject,"userId",String.class,getLoginUserInfo()==null?"":getLoginUserInfo().getUserId().toString());
        this.strictInsertFill(metaObject,"deleted",String.class,"0");


        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                Date current = ObjectUtil.isNotNull(baseEntity.getCreateTime())
                    ? baseEntity.getCreateTime() : new Date();
                baseEntity.setCreateTime(current);
                baseEntity.setUpdateTime(current);
                String username = StringUtils.isNotEmpty(baseEntity.getCreateBy())
                    ? baseEntity.getCreateBy() : getLoginUsername();
                // 当前已登录 且 创建人为空 则填充
                baseEntity.setCreateBy(username);
                // 当前已登录 且 更新人为空 则填充
                baseEntity.setUpdateBy(username);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新字段的自动插入
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateUserId", String.class, getLoginUserInfo()==null?"":getLoginUserInfo().getUserId().toString());
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                Date current = new Date();
                // 更新时间填充(不管为不为空)
                baseEntity.setUpdateTime(current);
                String username = getLoginUsername();
                // 当前已登录 更新人填充(不管为不为空)
                if (StringUtils.isNotEmpty(username)) {
                    baseEntity.setUpdateBy(username);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }

    /**
     * 获取登录用户名
     */
    private String getLoginUsername() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser.getUsername();
    }
    /**
     * 获取登录用户详细
     */
    private LoginUser getLoginUserInfo() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录");
            return null;
        }
        return loginUser;
    }

}
